package com.nsgf.library.ui.page.manager;

import static com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_COLLAPSED;
import static com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_HIDDEN;
import static com.nsgf.library.ui.page.manager.WorkOrderMapActivity.getJsonObject;

import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.databinding.FragmentNagfWorkOrderRecordBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.photopicker.widget.MultiPickResultView;
import com.nsgf.library.ui.adapter.ManagerDamListAdapter;
import com.nsgf.library.ui.adapter.ManagerDamTaskRecordListAdapter;
import com.nsgf.library.ui.page.BaseFragment;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.Kits;
import com.nsgf.library.utils.StringUtil;
import com.nsgf.library.utils.Utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 工单已办巡查记录
 */
public class WorkOrderAlreadyRecordFragment extends BaseFragment {

    public static WorkOrderAlreadyRecordFragment newInstance(WorkOrderDetailBean.DataBean dataBean) {
        WorkOrderAlreadyRecordFragment messageFragment = new WorkOrderAlreadyRecordFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable("dataBean", dataBean);
        messageFragment.setArguments(bundle);
        return messageFragment;

    }

    private WorkOrderDetailBean.DataBean getDataBean() {
        return getArguments().getParcelable("dataBean");
    }

    private WorkOrderAlreadyRecordFragmentStates mStates;

    FragmentNagfWorkOrderRecordBinding mBinding;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(WorkOrderAlreadyRecordFragmentStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);

    }

    private AccountRequester mAccountRequester;

    private ManagerDamListAdapter mAdapter;
    private ManagerDamTaskRecordListAdapter mAdapterItem;

    @Override
    protected DataBindingConfig getDataBindingConfig() {

        mAdapter = new ManagerDamListAdapter(getContext(), 2);
        mAdapterItem = new ManagerDamTaskRecordListAdapter(getContext());

        return new DataBindingConfig(R.layout.fragment_nagf_work_order_record, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy())
                .addBindingParam(BR.adapterItem, mAdapterItem)
                .addBindingParam(BR.adapter, mAdapter);
    }

    private BottomSheetBehavior<NestedScrollView> mBehavior;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        getLifecycle().addObserver(mAccountRequester);
        mBinding = (FragmentNagfWorkOrderRecordBinding) getBinding();

        mBehavior = BottomSheetBehavior.from(mBinding.bottomSheet);
        mBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        mBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {

                if (newState == STATE_HIDDEN) {
                    mBehavior.setState(STATE_COLLAPSED);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });

        mStates.list.set(getDataBean().getPositionVOS());
        mAdapter.notifyDataSetChanged();

        mAdapter.
                setOnItemClickListener((viewId, item1, position) -> {

                    for (WorkOrderDetailBean.DataBean.PtWorkOrderAbnormal abnormal : getDataBean().getAbnormalList()) {

                        for (WorkOrderDetailBean.DataBean.PositionVOSBean.ItemsBean itemsBean : item1.getItems()) {

                            if (abnormal.getAreaCode().concat(abnormal.getPositionCode()).concat(abnormal.getItemCode())
                                    .equals(itemsBean.getAreaCode().concat(itemsBean.getPositionCode()).concat(itemsBean.getItemCode()))) {

                                itemsBean.setAbnormalDescribe(abnormal.getAbnormalDescribe());
                                itemsBean.setLiveImageList(abnormal.getLiveImageList());
                            }
                        }
                    }

                    mStates.dataItem.set(item1.getItems());
                    mBinding.listItem.setVisibility(View.VISIBLE);
                    mBinding.coordinator.setVisibility(View.GONE);
                    index++;
                });

        mBinding.multiPickResultView.init(getActivity(), MultiPickResultView.ACTION_ONLY_SHOW, (ArrayList<WorkOrderDetailBean.FileDto>) getDataBean().getPhotos(), 3);
        mStates.detailBeanState.set(getDataBean());

        mBinding.webView.getWebView().clearHistory();
        String url = "file:///android_asset/roadLine/index.html?random=" + Kits.Date.getTimeStame();
        WebSettings mWebSettings = mBinding.webView.getWebView().getSettings();
        mWebSettings.setJavaScriptEnabled(true);//设置支持javaScript
        mBinding.webView.loadUrl(url);
        // 当页面加载完成后调用JavaScript方法
        mBinding.webView.getWebView().setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

//
//                /**
//                 * 默认巡查规划路线
//                 */
                if (!StringUtil.isEmpty(getDataBean().getPlanRoute())) {
                    List<List> lists = JSON.parseArray(getDataBean().getPlanRoute(), List.class);
                    JSONArray initArray = new JSONArray();
                    for (int i = 0; i < lists.size(); i++) {

                        String[] doubles = lists.get(i).toString().replace("[", "").replace("]", "").split(",");
                        WorkOrderDetailBean.DataBean.PositionVOSBean positionVOSBean = new WorkOrderDetailBean.DataBean.PositionVOSBean();
                        positionVOSBean.setLat(doubles[1]);
                        positionVOSBean.setLon(doubles[0]);

                        JSONObject initJson = getJsonObject(positionVOSBean);
                        initArray.add(initJson);
                    }
                    //绘制巡查初始路线
                    callJavaScriptDrawInitLineFunction(initArray);
                }

                //绘制巡查点
                uploadMaps();

                /**
                 * 实际巡查路线
                 */
                if (!StringUtil.isEmpty(getDataBean().getActualRoute())) {
                    List<List> lists = JSON.parseArray(getDataBean().getActualRoute(), List.class);
                    if (lists.size() < 2)
                        return;
                    JSONArray initArray = new JSONArray();
                    for (int i = 0; i < lists.size(); i++) {

                        String[] doubles = lists.get(i).toString().replace("[", "").replace("]", "").split(",");
                        WorkOrderDetailBean.DataBean.PositionVOSBean positionVOSBean = new WorkOrderDetailBean.DataBean.PositionVOSBean();
                        positionVOSBean.setLat(doubles[1]);
                        positionVOSBean.setLon(doubles[0]);

                        JSONObject initJson = getJsonObject(positionVOSBean);
                        initArray.add(initJson);
                    }
                    //绘制巡查路綫
                    callJavaScriptDrawPatrolLineFunction(initArray);

                }

            }
        });

        calculateDistance();

        // 开始巡检时间
        Calendar calendarStart = Calendar.getInstance();
        calendarStart.setTimeInMillis(Kits.Date.timeStrToSecond(mStates.detailBeanState.get().getStartHandleTime()));
        // 结束巡检时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(Kits.Date.timeStrToSecond(mStates.detailBeanState.get().getEndHandleTime()));

        mStates.damTime.set("巡查时间:" + (Kits.Date.millisToHMS(Kits.Date.calculateDuration(calendarStart, calendar))));

    }

    private void callJavaScriptDrawInitLineFunction(JSONArray list) {
        mBinding.webView.getWebView().evaluateJavascript("drawInitLine(" + "'" + list + "'" + ");", null);
    }

    /**
     * 巡查站点
     */
    private void uploadMaps() {

        JSONArray mapBeans = new JSONArray();
        for (WorkOrderDetailBean.DataBean.PositionVOSBean vosBean : getDataBean().getPositionVOS()) {
            vosBean.setStatus(1);
            JSONObject jsonObject = getJsonObject(vosBean);
            mapBeans.add(jsonObject);
        }
        callJavaScriptDrawInitPintFunction(mapBeans);

    }

    private void callJavaScriptDrawInitPintFunction(JSONArray list) {
        mBinding.webView.getWebView().evaluateJavascript("drawInitPint(" + "'" + list + "'" + ");", null);
    }

    /**
     * 绘制巡查路线
     *
     * @param list
     */
    private void callJavaScriptDrawPatrolLineFunction(JSONArray list) {
        mBinding.webView.getWebView().evaluateJavascript("drawPatrolLine(" + list + ");", null);
    }


    private DecimalFormat df = new DecimalFormat("#####0.00");

    private void calculateDistance() {
        double distance = 0.0;

        //加载初始巡查路线
        if (!StringUtil.isEmpty(getDataBean().getActualRoute())) {
            List<List> lists = JSON.parseArray(getDataBean().getActualRoute(), List.class);
            for (int i = 1; i < lists.size(); i++) {

                String[] doubles = lists.get(i).toString().replace("[", "").replace("]", "").split(",");

                String[] doublesOld = lists.get(i - 1).toString().replace("[", "").replace("]", "").split(",");

                distance = distance + Utils.calculateDistance(Double.parseDouble(doubles[1]),
                        Double.parseDouble(doubles[0]),
                        Double.parseDouble(doublesOld[1]),
                        Double.parseDouble(doublesOld[0]));
            }
        }
        mStates.distance.set("里程:" + df.format(distance / 1000) + "km");

    }

    public static class WorkOrderAlreadyRecordFragmentStates extends StateHolder {

        public final State<String> name = new State<>(UserInfo.getInstance().getProjectName());
        public final State<String> appLog = new State<>(UserInfo.getInstance().getAppLog());

        public final State<List<WorkOrderDetailBean.DataBean.PositionVOSBean>> list = new State<>(new ArrayList<>());

        public final State<WorkOrderDetailBean.DataBean> detailBeanState = new State<WorkOrderDetailBean.DataBean>(null);

        public final State<WorkOrderDetailBean.DataBean.PositionVOSBean> data = new State<>(null);
        public final State<List<WorkOrderDetailBean.DataBean.PositionVOSBean.ItemsBean>> dataItem = new State<>(null);

        public final State<Boolean> loadingVisible = new State<>(false);
        public final State<String> distance = new State<>("");
        public final State<String> damTime = new State<>("巡查时间:1小时");

    }

    /**
     * 当前页数
     */
    private int index = 0;

    public class ClickProxy {

        public void next() {

            if (index == 2) {
                index--;
                mBinding.listItem.setVisibility(View.GONE);
                mBinding.coordinator.setVisibility(View.VISIBLE);
            } else if (index == 1) {
                mBinding.listItem.setVisibility(View.VISIBLE);
                mBinding.coordinator.setVisibility(View.GONE);
                index++;
            } else {
                index++;
                mBinding.coordinator.setVisibility(View.VISIBLE);
                mBinding.llRecordOne.setVisibility(View.GONE);
                mBinding.btnLogin.setText("上一步");
            }

        }
    }
}
